<template>
  <view class="form-page">
    <!-- 页面标题 -->
    <view class="page-title">form 表单</view>
    
    <!-- 表单容器：绑定提交、重置事件 -->
    <form @submit="formSubmit" @reset="formReset">
      <!-- 姓名输入 -->
      <view class="form-item">
        <view class="item-label">姓名</view>
        <input class="item-input" name="nickname" placeholder="请输入姓名" />
      </view>

      <!-- 性别单选 -->
      <view class="form-item">
        <view class="item-label">性别</view>
        <radio-group name="gender">
          <radio value="男" checked>男</radio>
          <radio value="女">女</radio>
        </radio-group>
      </view>

      <!-- 爱好复选 -->
      <view class="form-item">
        <view class="item-label">爱好</view>
        <checkbox-group name="loves">
          <checkbox value="读书">读书</checkbox>
          <checkbox value="写字">写字</checkbox>
        </checkbox-group>
      </view>

      <!-- 年龄滑块 -->
      <view class="form-item">
        <view class="item-label">年龄</view>
        <slider value="20" name="age" show-value></slider>
      </view>

      <!-- 保留选项（开关） -->
      <view class="form-item">
        <view class="item-label">保留选项</view>
        <switch name="switch" :checked="false"></switch>
      </view>

      <!-- 提交/重置按钮 -->
      <view class="form-buttons">
        <button form-type="submit">Submit</button>
        <button form-type="reset">ResetReset</button>
      </view>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 表单相关初始值（可选，用于手动控制重置后状态）
      gender: '男',
      loves: [],
      age: 20,
      switchVal: false
    };
  },
  methods: {
    // 表单提交事件
    formSubmit(e) {
      console.log('表单提交，数据为：', JSON.stringify(e.detail.value));
      
      // 定义表单验证规则
      const rules = [
        { name: 'nickname', type: 'string', rule: '1,3', msg: '姓名应为 1-3 个字符' },
        { name: 'gender', type: 'in', rule: '男,女', msg: '请选择性别' },
        { name: 'loves', type: 'notNull', rule: '', msg: '请选择爱好' }
      ];
      
      // 执行表单验证
      const { isValid, errorMsg } = this.validateForm(e.detail.value, rules);
      
      if (isValid) {
        uni.showToast({ title: '验证通过', icon: 'none' });
      } else {
        uni.showToast({ title: errorMsg, icon: 'none' });
      }
      
      // 弹窗展示表单数据
      uni.showModal({
        content: '表单数据：' + JSON.stringify(e.detail.value),
        showCancel: false
      });
    },

    // 表单重置事件
    formReset() {
      console.log('表单已重置');
      // 重置自定义数据（若需手动同步状态）
      this.gender = '男';
      this.loves = [];
      this.age = 20;
      this.switchVal = false;
    },

    // 表单验证工具（模拟简易验证逻辑）
    validateForm(formData, rules) {
      for (let i = 0; i < rules.length; i++) {
        const { name, type, rule, msg } = rules[i];
        const value = formData[name];

        // 字符串长度验证
        if (type === 'string') {
          const [min, max] = rule.split(',');
          const len = (value || '').length;
          if (len < min || len > max) {
            return { isValid: false, errorMsg: msg };
          }
        }

        // 枚举值验证（是否在指定选项中）
        if (type === 'in') {
          const options = rule.split(',');
          if (!options.includes(value)) {
            return { isValid: false, errorMsg: msg };
          }
        }

        // 非空验证（数组是否有选中项）
        if (type === 'notNull') {
          if (!value || value.length === 0) {
            return { isValid: false, errorMsg: msg };
          }
        }
      }
      return { isValid: true, errorMsg: '' };
    }
  }
};
</script>

<style>
.form-page {
  padding: 20rpx;
  background-color: #fff;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
}

.item-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.item-input {
  border: 1rpx solid #ddd;
  border-radius: 6rpx;
  padding: 15rpx;
  font-size: 28rpx;
}

radio-group, checkbox-group {
  display: flex;
  flex-direction: row;
}

radio, checkbox {
  margin-right: 30rpx;
}

.form-buttons {
  display: flex;
  flex-direction: column;
}

button {
  margin-bottom: 20rpx;
}
</style>